﻿using ConfExpert.Utility;

using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class POKodSihirbazi : XPopupForm
    {
        public List<Kod> Kodlar;
        DataTable dtBenzer = null;

        public class Kod
        {
            private int productId = -1;
            public int ProductId
            {
                get { return productId; }
                set { productId = value; }
            }

            private string musteriKodu;
            public string MusteriKodu
            {
                get { return musteriKodu; }
                set { musteriKodu = value; }
            }

            private string ureticiKodu;
            public string UreticiKodu
            {
                get { return ureticiKodu; }
                set { ureticiKodu = value; }
            }

            private int kcustomerId = -1;
            public int KCustomerId
            {
                get { return kcustomerId; }
                set { kcustomerId = value; }
            }

            private int kVendorId = -1;
            public int KVendorId
            {
                get { return kVendorId; }
                set { kVendorId = value; }
            }

            private string kaliteAciklama;
            public string KaliteAciklama
            {
                get { return kaliteAciklama; }
                set { kaliteAciklama = value; }
            }

            private int rowHandle = -1;
            public int RowHandle
            {
                get { return rowHandle; }
                set { rowHandle = value; }
            }

            private int pOLinesId = -1;
            public int POLinesId
            {
                get { return pOLinesId; }
                set { pOLinesId = value; }
            }
        }

        public POKodSihirbazi(List<Kod> kodlar)
        {
            InitializeComponent();
            this.Kodlar = kodlar;
        }

        void POKodSihirbazi_Load(object sender, EventArgs e)
        {
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

            barButtonItem1.ItemClick += barButtonItem1_ItemClick;

            gv.FocusedRowChanged += gv_FocusedRowChanged;
            gv.RowCellStyle += gv_RowCellStyle;
            //gv.Images = bgvIcons;
            gv.CellValueChanged += gv_CellValueChanged;

            DataTable dtKodlar = Kodlar.ToDataTable();
            dtKodlar.Columns.Add("Aksiyon", typeof(int));

            DataTable aksiyon = new DataTable();
            aksiyon.Columns.Add("AksiyonId", typeof(int));
            aksiyon.Columns.Add("Aksiyon", typeof(string));



            if (isKD)
            {
                aksiyon.Rows.Add(1, "ÜK ile Kart Aç");
                aksiyon.Rows.Add(2, "MK ile Kart Aç");
            }
            aksiyon.Rows.Add(3, "Seçili Artikeli Kullan");
            aksiyon.Rows.Add(4, "İşlem Yapma");

            RepositoryItemGridLookUpEdit ri = GetCustomGLE(aksiyon, "Aksiyon", "AksiyonId");
            ri.TextEditStyle = TextEditStyles.DisableTextEditor;

            List<string> listCode = new List<string>();
            foreach (DataRow dr in dtKodlar.Rows)
            {
                string MK = dr["MusteriKodu"].ToStr();
                if (MK != "" && !listCode.Contains(MK))
                    listCode.Add(MK);

                string UK = dr["UreticiKodu"].ToStr();
                if (UK != "" && !listCode.Contains(UK))
                    listCode.Add(UK);
            }
            string codes = String.Join(",", listCode.ToList());
            dtBenzer = ExecuteDataTable("FindSimilarByCodeTOPLU", codes);

            foreach (DataRow dr in dtKodlar.Rows)
            {
                if (dr["ProductId"].ToInt(-1) > 0)
                {
                    dr["Aksiyon"] = 3;
                }
                else
                {
                    DataRow[] UK100 = dtBenzer.Select("Score=100 and Kod='" + dr["MusteriKodu"] + "'");

                    if (UK100.Length > 0)
                    {
                        dr["Aksiyon"] = 3;
                        dr["ProductId"] = UK100[0]["ProductId"];
                    }
                    else if (!isKD)
                    {
                        dr["Aksiyon"] = 3;
                    }
                    else if (dr["MusteriKodu"].ToStr() != "")
                    {
                        dr["Aksiyon"] = 2;
                    }
                    else if (dr["UreticiKodu"].ToStr() != "")
                    {
                        dr["Aksiyon"] = 1;
                    }
                }
            }

            gv.Init(dtKodlar);
            gv.Columns["Aksiyon"].ColumnEdit = ri;
            ri.EditValueChanged += ri_EditValueChanged;

            gv.MakeReadOnly("ProductId", "Aksiyon", "KVendorId", "KCustomerId");
            gv.MakeColumnInvisible("RowHandle", "POLinesId");
            gv.SetCaptions("MusteriKodu:Müşteri Kodu", "KCustomerId:Müşteri", "KVendorId:Üretici", "UreticiKodu:Üretici Kodu", "KaliteAciklama:Teknik Özellikler");
            gv.Columns["Aksiyon"].VisibleIndex = 0;

            gv.SetViewCaption("Artikeller");
            gv.BestFitColumns();
            //gv.Columns["Aksiyon"].Width = 150;

            InitBenzerGrid(gvMK, "Benzer Kodlar");
            GridMenu gm = GridManager.GetManager(gvMK).GridMenu;
            gm.AddMenu("Bu artikeli kullan", gvBenzer_DoubleClick);

            splitContainerControl1.SplitterPosition = splitContainerControl1.Width / 2;
            splitContainerControl1.AutoSize();
        }

        void gv_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "ProductId")
                gv.SetFocusedRowCellValue("Aksiyon", 3);

            gv.BestFitColumns();
        }

        void InitBenzerGrid(GridView gv, string caption)
        {
            gv.SetViewCaption(caption);
            gv.Appearance.ViewCaption.TextOptions.HAlignment = HorzAlignment.Default;
            gv.DoubleClick += gvBenzer_DoubleClick;
        }

        void gvBenzer_DoubleClick(object sender, EventArgs e)
        {
            //GridView gvBenzer = sender as GridView;
            int productId = gvMK.GetFocusedRowCellValue("ProductId").ToInt(-1);
            if (productId > 0)
            {
                gv.SetFocusedRowCellValue("ProductId", productId);
                gv.SetFocusedRowCellValue("Aksiyon", 3);
            }
        }


        void ri_EditValueChanged(object sender, EventArgs e)
        {
            gv.EndEditing();
        }

        void gv_DoubleClick(object sender, EventArgs e)
        {
            GridView gvSender = sender as GridView;
            int ProductId = intParse(gvSender.GetFocusedRowCellValue("ProductId"));
            if (ProductId > 0)
            {
                gv.SetFocusedRowCellValue("ProductId", ProductId);
                gv.SetFocusedRowCellValue("AksiyonId", 3);
            }
        }

        void gv_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                int aksiyon = gv.GetRowCellValue(e.RowHandle, "Aksiyon").ToInt(-1);

                switch (e.Column.FieldName)
                {
                    case "Aksiyon":
                        //if (e.RowHandle == gv.FocusedRowHandle)
                        e.Appearance.Font = new System.Drawing.Font(e.Appearance.Font, FontStyle.Bold);
                        e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
                        break;

                    case "KCustomerId":
                        if (aksiyon == 2)
                            e.Appearance.BackColor = e.Appearance.BackColor2 = Color.SkyBlue;   //LightGray;
                        else
                            e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
                        break;

                    case "KVendorId":
                        if (aksiyon == 1)
                            e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   //LightGray;
                        else
                            e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
                        break;

                    case "MusteriKodu":
                        if (aksiyon == 2)
                            e.Appearance.BackColor = e.Appearance.BackColor2 = Color.SkyBlue;   //LightGray;
                        else
                            e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
                        break;

                    case "UreticiKodu":
                        if (aksiyon == 1)
                            e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   //LightGray;
                        else
                            e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
                        break;

                    case "PRO":
                        if (aksiyon == 3)
                            e.Appearance.BackColor = e.Appearance.BackColor2 = Color.Gold; //LightGray;
                        else
                            e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
                        break;
                }
            }
        }

        void gv_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
                gcMK.DataSource = null;
            else
            {
                int aksiyon = gv.GetFocusedRowCellValue("Aksiyon").ToInt(-1);
                if (aksiyon == 2)
                    txtInfo.Caption = gv.GetFocusedRowCellValue("MusteriKodu").ToString();
                else if (aksiyon == 1)
                    txtInfo.Caption = gv.GetFocusedRowCellValue("UreticiKodu").ToString();
                else if (aksiyon == 3)
                    txtInfo.Caption = gv.GetFocusedRowCellDisplayText("ProductId").ToString();
                else if (aksiyon == 4)
                    txtInfo.Caption = "Artikel Belirlenmeyecek";

                Kod kod = Kodlar[e.FocusedRowHandle];
                string MK = kod.MusteriKodu;
                string UK = kod.UreticiKodu;
                InitSimilarGrid(gvMK, MK, UK);
            }
        }

        void InitSimilarGrid(GridView gv, string MK, string UK)
        {
            DataRow[] drs = dtBenzer.Select("Kod='" + MK + "' OR Kod='" + UK + "'");
            DataTable dt = dtBenzer.Clone();
            if (drs.Length > 0)
                dt = drs.CopyToDataTable();

            gv.Init(dt);
            gv.MakeReadOnly();
            gv.MakeRowSelectable();
            gv.FormatAsPercentage("Score");
            gv.Columns["Score"].Width = 30;
            gv.Columns["Score"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
            gv.MakeColumnInvisible("Kod", "KodId");
            gv.SetCaptions("Customer:Müşteri", "Vendor:Üretici", "Score:Benzerlik", "Name:Kod", "Tip:Kod Tipi");
            gv.BestFitColumns();
        }

        void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gv.EndEditing();

            DataTable dt = gv.DataTable();
            DataRow[] dtUK = dt.Select("Aksiyon = 1 and isnull(KVendorId,-1) = -1");
            DataRow[] dtMK = dt.Select("Aksiyon = 2 and isnull(KCustomerId,-1) = -1");
            DataRow[] dtSK = dt.Select("Aksiyon = 3 and isnull(ProductId,-1) = -1");

            DataRow[] dtIgnore = dt.Select("Aksiyon = 4");
            foreach (DataRow dr in dtIgnore)
            {
                int rowHandle = dr["RowHandle"].ToInt(-1);
                Kodlar.Find(p => p.RowHandle == rowHandle).ProductId = -1;
            }

            DataRow[] dtProd = dt.Select("Aksiyon = 3 and ProductId is not null");
            foreach (DataRow dr in dtProd)
            {
                int productId = dr["ProductId"].ToInt(-1);
                int rowHandle = dr["RowHandle"].ToInt(-1);
                Kodlar.Find(p => p.RowHandle == rowHandle).ProductId = productId;
            }

            if (dtMK.Length + dtUK.Length + dtSK.Length > 0)
            {
                ShowInfoMessage("Lütfen soldaki gridin renklendirilmiş hücrelerini doldurun.");

                //ShowInfoMessage("ÜK ile kart açmak için Üretici, MK ile kart açmak için Müşteri, Seçili artikeli kullanmak için Artikel seçilmelidir.");
            }
            else
            {
                DataRow[] acilacakKartlar = gv.DataTable().Select("Aksiyon in(1,2)");
                if (acilacakKartlar.Length > 0)
                {
                    dt = acilacakKartlar.CopyToDataTable();

                    string xml = dt.Serialize();
                    DataTable dtNew = ExecuteDataTable("POKartAcSihirbaz", xml, WhoAmI);

                    if (dtNew.Columns.Contains("Hata"))
                    {
                        XtraMessageBox.Show(dtNew.Rows[0][0].ToString(), "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    AppSession.MainForm.RefreshData();

                    foreach (DataRow dr in dtNew.Rows)
                    {
                        int rowHandle = (int)dr["RowHandle"];
                        int productId = (int)dr["ProductId"];
                        Kodlar.Find(p => p.RowHandle == rowHandle).ProductId = productId;
                    }
                }
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        private void barButtonItem1_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }
    }
}